package com.example.yiwei.crm.view.activity.coordinationActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.example.yiwei.crm.R;
import com.example.yiwei.crm.base.baseClass;
import com.example.yiwei.crm.dao.managerDao;
import com.example.yiwei.crm.dao_impl.managerDaoImpl;
import com.example.yiwei.crm.data.GetExchange;
import com.example.yiwei.crm.entity.ExchangeEntity;
import com.example.yiwei.crm.entity.JLfsEntity;
import com.example.yiwei.crm.entity.managerEntity;
import com.example.yiwei.crm.json.JLfsJson;
import com.example.yiwei.crm.util.NetWorkUtils;
import com.example.yiwei.crm.util.SC;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class AddJLActivity extends AppCompatActivity {

    private TextView tv_bf_time,add_jl;
    private EditText tv_jll,tv_pj;
    private Spinner sp_jl_fs,sp_jl_r;
    private ImageView img_back,img_commit;
    private TimePickerView mpv;
    private String time;
    private List<managerEntity> managerList = new ArrayList<>();
    private Button button;
    private List<String> name_list=new ArrayList<>();
    private SharedPreferences sp;
    private ArrayAdapter adapter1,adapter2;
    private String managerName,fs_name;
    private int  manager_id,fs_id;
    private List<JLfsEntity> fslist;
    private List<String> fs_list = new ArrayList<>();
    private int dock_id;
    private ExchangeEntity entity;
    private Date date1,date2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_jl);
        sp = getSharedPreferences("login", Context.MODE_PRIVATE);
        tv_bf_time = (TextView) findViewById(R.id.add_jl_bf_time);
        tv_jll = (EditText) findViewById(R.id.add_jl_jiaoliuliang);
        tv_pj  = (EditText) findViewById(R.id.add_jl_pingjia);
        sp_jl_fs = (Spinner) findViewById(R.id.add_jl_bf_fs);
        sp_jl_r = (Spinner) findViewById(R.id.add_jl_people);
        add_jl = (TextView) findViewById(R.id.add_jl);
        img_back = (ImageView) findViewById(R.id.coording_communication_add_img_back);
        img_commit = (ImageView) findViewById(R.id.coording_communication_add_img_commit);
        button = (Button) findViewById(R.id.add_jl_bf_time_btn);
        tv_jll.setInputType(InputType.TYPE_CLASS_NUMBER);
        dock_id = getIntent().getIntExtra("dockid",0);
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //创建选择器
        mpv = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH_DAY);
        //设置时间范围
        Calendar calendar = Calendar.getInstance();
        mpv.setRange(calendar.get(Calendar.YEAR) - 100, calendar.get(Calendar.YEAR) + 100);
        //插入时间
        mpv.setTime(new Date());
        //选择监听
        mpv.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

            @Override
            public void onTimeSelect(Date date) {
                date1 = date;
                time=getTime(date);
                tv_bf_time.setText(time);
            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mpv.show();
            }
        });
        if ("update".equals(getIntent().getStringExtra("tag"))){
            setMessage();
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                SC sc = new SC();
                JSONObject object = sc.storage(sp);
                try {
                    object.put("admin",sp.getString("admin",null));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String json = object.toString();
                managerDao manaDao=new managerDaoImpl();
                managerList=manaDao.queryAllManager(baseClass.query_manager_url,json);
                JSONObject object1 = sc.storage(sp);
                String json1 = object1.toString();
                String result = NetWorkUtils.getCount(baseClass.find_bf_fs_sp_URL,json1);
                fslist = JLfsJson.get(result);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i2=0;i2<managerList.size();i2++){
                            name_list.add( managerList.get(i2).getManager_name());
                        }
                        adapter1 = new ArrayAdapter(AddJLActivity.this,R.layout.spinner_display_style,R.id.txtvwSpinner, name_list);
                        adapter1.setDropDownViewResource(R.layout.spinner_dropdown_style);
                        sp_jl_r.setAdapter(adapter1);

                        sp_jl_r.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                                managerName=managerList.get(i).getManager_name();
                                manager_id = managerList.get(i).getManager_id();
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> adapterView) {

                            }
                        });
                        for (int i3 = 0;i3<fslist.size();i3++){
                            fs_list.add(fslist.get(i3).getName());
                        }
                        adapter2 = new ArrayAdapter(AddJLActivity.this,R.layout.spinner_display_style,R.id.txtvwSpinner, fs_list);
                        adapter2.setDropDownViewResource(R.layout.spinner_dropdown_style);
                        sp_jl_fs.setAdapter(adapter2);
                        sp_jl_fs.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                fs_name = fslist.get(position).getName();
                                fs_id = fslist.get(position).getId();
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });
                        if ("update".equals(getIntent().getStringExtra("tag"))){
                            entity = GetExchange.exchangeEntity;
                            for (int i = 0;i<name_list.size();i++){
                                if (name_list.get(i).equals(entity.getManger_name())){
                                    sp_jl_r.setSelection(i);
                                }
                            }
                            for (int i = 0;i<fslist.size();i++){
                                if (fslist.get(i).getId()==entity.getFs_id()){
                                    sp_jl_fs.setSelection(i);
                                }
                            }
                        }
                    }
                });

            }
        }).start();
        img_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String a = getTime(new Date());
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    date2 =  formatter.parse(a);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                if (tv_bf_time.getText().toString().equals("")){
                    Toast.makeText(AddJLActivity.this, "请选择拜访时间", Toast.LENGTH_SHORT).show();
                }else if (date1!=null&&date2!=null&&date2.after(date1)){
                    Toast.makeText(AddJLActivity.this, "拜访时间不能早于当前时间", Toast.LENGTH_SHORT).show();
                }else if (tv_jll.getText().toString().equals("")){
                    Toast.makeText(AddJLActivity.this, "请输入交流量", Toast.LENGTH_SHORT).show();
                }else if (tv_pj.getText().toString().equals("")){
                    Toast.makeText(AddJLActivity.this, "请输入主任评价", Toast.LENGTH_SHORT).show();
                }else {
                    add();
                }
            }
        });
    }

    private void setMessage() {
        add_jl.setText("修改交流");
        entity = GetExchange.exchangeEntity;
        tv_bf_time.setText(entity.getBf_time());
        tv_pj.setText(entity.getYijian());
        tv_jll.setText(entity.getJiaoliuliang());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        try {
            date1 =  formatter.parse(entity.getBf_time());
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private void add() {
        img_commit.setVisibility(View.GONE);
        new Thread(new Runnable() {
            @Override
            public void run() {
                SC sc = new SC();
                JSONObject object = sc.storage(sp);
                try {
                    object.put("KJA02",tv_bf_time.getText().toString());
                    object.put("KXA01",dock_id);
                    object.put("ABF01",fs_id);
                    object.put("KJA08",tv_jll.getText().toString());
                    object.put("KJA03",manager_id);
                    object.put("KJA09",tv_pj.getText().toString());
                    if ("update".equals(getIntent().getStringExtra("tag"))){
                        object.put("addoredit","edit");
                        object.put("KJA01",entity.getId());
                    }else {
                        object.put("addoredit","add");
                    }
                    object.put("KJA04",managerName);
                    object.put("CID03",sp.getString("CID03",null));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String json = object.toString();
                final String result = NetWorkUtils.getCount(baseClass.addoredit_jl_URL,json);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        boolean b = false;
                        try {
                            JSONObject object1 = new JSONObject(result);
                             b = object1.getBoolean("ifsuccess");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (b){
                            finish();
                        }else {
                            img_commit.setVisibility(View.VISIBLE);
                            Toast.makeText(AddJLActivity.this, "添加失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }).start();
    }

    public static String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }
}
